<template>
  <div class="tableMore">
    <div class="feature">table单元格合并</div>
    <el-form
      :model="form"
      ref="form"
      label-width="100px"
      size="mini"
      class="my-form"
      @submit.native.prevent
    >
      <div class="searchDiv">
        <el-form-item label="机构名称">
          <el-input
            clearable
            style="width: 350px"
            v-model="form.search"
            placeholder="请输入机构名称"
            ref="search"
            @keyup.enter.native="search()"
          ></el-input>
          <el-button
            type="primary"
            plain
            @click="search()"
            style="margin-left: 10px"
            >搜索</el-button
          >
        </el-form-item>
      </div>
    </el-form>
    <el-divider></el-divider>
    <div class="userTable">
      <el-table
        ref="isExpand"
        :data="tables"
        size="mini"
        stripe
        v-loading="table_loading"
        row-key="id"
        @sort-change="changeTableSort"
        :tree-props="{
          children: 'child_list',
          hasChildren: 'hasChildren',
        }"
        @expand-change="changeTableTree"
        :row-style="rowClassRender"
        v-if="tableTree"
        :default-expand-all="expandStatus"
      >
        <el-table-column
          label="ID"
          width="150"
          prop="id"
        ></el-table-column>
        <el-table-column label="机构名称" prop="level_name">
          <template slot-scope="{ row }">
            <span v-html="row.level_name"></span>
          </template>
        </el-table-column>
        <el-table-column
          label="活动预算"
          prop="p_max_amount"
          :sortable="'custom'"
          :sort-orders="['ascending', 'descending']"
          width="135"
        >
          <template slot-scope="{ row }">
            <b>￥{{ row.p_max_amount }}</b>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        search: "",
      },
      sort: "", //排序类型code
      tables: [],
      currentRowId: null,
      expandedRowsStatus: false,
      expandKeys: [],
      expandKeysId: "",
      oldTable: [],
      expandStatus: false,
      tableTree: true,
    };
  },
  methods: {
    //table树形结构事件
    changeTableTree(row, expandedRows) {
      console.log("row", row);
      console.log("expandedRows", expandedRows);
      this.currentRowId = row.id;
      this.expandedRowsStatus = expandedRows;
    },

    rowClassRender({ row }) {
      if (row.id == this.currentRowId && this.expandedRowsStatus) {
        return { "font-weight": "bold" };
        //return { "background": "#ecf5ff" };
      } else {
        return "";
      }
    },

    //table排序事件
    changeTableSort(column) {
      //获取字段名称和排序类型
      let fieldName = column.prop,
        sortingType = column.order;
      /**
       * 升序：ascending
       * 降序：descending
       */

      if (sortingType == null) {
        console.log("取消了排序", this.sortColumn);
      }

      //升序
      if (sortingType == "ascending") {
        if (fieldName == "p_max_amount") {
          this.sort = 0;
        } else if (fieldName == "p_take_amount") {
          this.sort = 2;
        }
      }

      //降序
      if (sortingType == "descending") {
        if (fieldName == "p_max_amount") {
          this.sort = 1;
        }
      }
      console.log("this.sort", this.sort);
    },

    //加载列表
    initData() {
      this.tables = [];
      this.expandKeys = [];
      this.oldTable = [];
      this.expandStatus = false;
      this.table_loading = true;
      let data = {
        id: 5340,
        level_name: "市公司",
        level_type: "市公司",
        p_max_amount: "17542.00",
        p_remain_amount: "1710.00",
        p_take_amount: "15832.00",
        amountData: [
          { name: "已派发", value: 15832 },
          { name: "剩余额度", value: 1710 },
          { name: "总额度", value: 17542 },
        ],
        child_list: [
          {
            id: 5341,
            level_name: "吴川营业所",
            level_type: "区县",
            p_max_amount: "2742.00",
            p_remain_amount: "0.00",
            p_take_amount: "2742.00",
            amountData: [
              { name: "已派发", value: 158 },
              { name: "剩余额度", value: 42 },
              { name: "总额度", value: 200 },
            ],
            child_list: [
              {
                id: 5342,
                level_name: "黄坡营业所",
                level_type: "网点",
                p_max_amount: "2742.00",
                p_remain_amount: "0.00",
                p_take_amount: "742.00",
                amountData: [
                  { name: "已派发", value: 158 },
                  { name: "剩余额度", value: 42 },
                  { name: "总额度", value: 200 },
                ],
              },
            ],
          },
          {
            id: 5343,
            level_name: "廉江营业所",
            level_type: "区县",
            p_max_amount: "2742.00",
            p_remain_amount: "0.00",
            p_take_amount: "270.00",
            amountData: [
              { name: "已派发", value: 158 },
              { name: "剩余额度", value: 42 },
              { name: "总额度", value: 200 },
            ],
            child_list: [],
          },
        ],
      };
      if (Object.keys(data).length != 0) {
        this.$nextTick(() => {
          this.tableTree = true;
        });
        this.tables.push(data); //table要渲染的数据
        this.oldTable.push(data); //原始数据
        //默认展开树状结构的第一层
        this.$nextTick(() => {
          this.$refs.isExpand.toggleRowExpansion(
            this.tables[0],
            true
          );
        });
      }
      this.table_loading = false;
    },

    search() {
      if (this.form.search) {
        this.tableTree = false;
        this.expandStatus = true;
        this.$nextTick(() => {
          this.tableTree = true;
        });
        this.table_loading = true;
        this.rebuildData(
          this.form.search,
          JSON.parse(JSON.stringify(this.oldTable))
        );
      } else {
        this.tableTree = false;
        this.expandStatus = false;
        this.tables = JSON.parse(JSON.stringify(this.oldTable));
        this.$nextTick(() => {
          this.tableTree = true;
          if (this.tableTree) {
            //默认展开树状结构的第一层
            this.$nextTick(() => {
              this.$refs.isExpand.toggleRowExpansion(
                this.tables[0],
                true
              );
            });
          }
        });
      }
    },

    //前端搜索
    rebuildData(value, arr) {
      this.tables = [];
      if (!arr) {
        return [];
      }
      const newArr = [];
      // console.log("arr", arr);
      arr.forEach((element) => {
        // indexOf用来判读当前节点level_name字段是否包含所搜索的字符串value
        // 返回值：包含则返回索引值，反之返回-1
        if (element.level_name.indexOf(value) > -1) {
          let childList = element.child_list;
          childList.map((item) => {
            item.level_name = this.brightKeyword(item.level_name);
          });
          const ab = this.rebuildData(value, childList);
          const obj = {
            ...element,
            child_list: ab,
          };
          newArr.push(obj);
        } else {
          // 判断当前节点知否有子节点，并且子节点中有数据，有数据继续递归查找
          if (element.child_list && element.child_list.length > 0) {
            let childList = element.child_list;
            childList.map((item) => {
              item.level_name = this.brightKeyword(item.level_name);
            });
            const ab = this.rebuildData(value, childList);
            const obj = {
              ...element,
              child_list: ab,
            };
            if (ab && ab.length > 0) {
              newArr.push(obj);
            }
          }
        }
      });
      if (newArr.length == 0) {
        this.table_loading = false;
        this.expandStatus = true;
      }
      this.tables = newArr;
      console.log("this.tables", this.tables);
      return newArr;
    },

    //高亮设置
    brightKeyword(val) {
      let search = this.form.search; //判断这个字段中是否包含keyword ，如果包含的话，就把这个字段中的那一部分进行替换成html字符
      if (val.indexOf(search) !== -1) {
        return val.replace(
          search,
          `<span style='color: #f80808;'>${search}</span>`
        );
      } else {
        return val;
      }
    },
  },

  created() {
    this.initData();
  },
};
</script>

<style lang="scss" scoped>
.feature {
  text-align: left;
  margin-bottom: 20px;
  line-height: 22px;
  font-size: 14px;
}
.userTable ::v-deep .el-table th.is-leaf,
.userTable ::v-deep .el-table .cell {
  text-align: center;
}
</style>
